package id.co.rho.scoring.cid.client.utils;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.data.BaseTreeModel;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.google.gwt.user.client.ui.Widget;

import id.co.rho.scoring.cid.client.helper.MenuFolder;
import id.co.rho.scoring.cid.client.helper.ModelMenuItem;
import id.co.rho.scoring.cid.client.mvc.AppView;
import id.co.rho.scoring.cid.shared.model.FunctionGroupModel;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class NavigationMenuUtils {
	
	public NavigationMenuUtils() {
		super();
	}

	public void updateInboxCount(TreeStore<ModelData> treeStore){
    	if(treeStore.findModel("id","inboxMenu")!=null){
	        BaseTreeModel searchItem = (BaseTreeModel) treeStore.findModel("id","inboxMenu");
		    Integer inboxCount = Registry.<Integer>get("inboxCount");
		    if (inboxCount != null) {
		        searchItem.set("name", "InBox (" + inboxCount + ")");
		        treeStore.update(searchItem);
		    }
    	}
    }
	
	public void updateMenuNavigation(List listRole){
    	List<String> functionCodeList = FunctionGroupModel.getListAllFunctionCode(listRole);
    	ContentPanel navPanel = (ContentPanel) Registry.get(AppView.WEST_PANEL);
    	TreePanel<ModelData> tree; 
    	Widget w = navPanel.getWidget(0);
    	if(w instanceof TreePanel){
    		tree = (TreePanel<ModelData>) w;    		
    		ModelData[] model = MenuFolder.getMenu();
    		List models = Arrays.asList(model);
    		List filteredModels = new ArrayList();
            
            ModelMenuItem itm;
            for(Iterator<Object> it = models.iterator(); it.hasNext(); ){
            	itm = (ModelMenuItem)it.next();
            	if(functionCodeList.contains(itm.getFunctionCode())){
            		filteredModels.add(itm);
            	}
            }
            tree.getStore().removeAll();
            tree.getStore().add(filteredModels, true);
    	}    	
    }
	
}
